package com.lrh.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lrh.reggie.common.BaseContext;
import com.lrh.reggie.common.CustomException;
import com.lrh.reggie.common.R;
import com.lrh.reggie.dto.OrdersDto;
import com.lrh.reggie.entity.*;
import com.lrh.reggie.mapper.OrdersMapper;
import com.lrh.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    public Page<Orders> getAllPage(int page, int pageSize, Long number, String beginTime, String endTime) {
        //前端请求的数据是 http://localhost:8080/order/page?page=1&pageSize=10&
        // beginTime=2024-11-06%2000%3A00%3A00&endTime=2024-12-19%2023%3A59%3A59
        Page<Orders> pageInfo = new Page<>();

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        // 3.1 添加查询条件：按下单时间降序排列
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //自己写的考虑的不全面少了对
        // 1.2 根据订单状态进行筛选   不知道是否实现
        //1.3 根据支付方式进行筛选     不知道是否实现
        //1.4 结账时间进行时间筛选
//        queryWrapper.like(number != null, Orders::getNumber, number);
//        queryWrapper.orderByDesc(Orders::getCheckoutTime).orderByAsc(Orders::getOrderTime);

        //链式编程写查询条件
        queryWrapper.like(number != null, Orders::getNumber, number)
                //前面加上判定条件是十分必要的，用户没有填写该数据，查询条件上就不添加它
                .gt(StringUtils.isNotBlank(beginTime), Orders::getOrderTime, beginTime)//大于起始时间 gt()
                .lt(StringUtils.isNotBlank(endTime), Orders::getOrderTime, endTime);//小于结束时间  lt()

        ordersService.page(pageInfo, queryWrapper);

        return pageInfo;
    }

    /**
     * 修改订单状态   自己写的 有问题  没有用到
     *
     * @param status
     * @param id
     */
    @Override
    public void updateStatus(Integer status, Long id) {

//        Orders orders = new Orders();
        Orders order = ordersService.getById(id);

        order.setStatus(status);

        ordersService.updateById(order);
//        orders.setStatus(status);

//        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
//
//        queryWrapper.eq(Orders::getId, id);
//
//        ordersService.update(order,queryWrapper);
    }


    // 获取订单分页展示
    @Override
    public Page<OrdersDto> getPage(int page, int pageSize) {
        // 1.创建分页封装器
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        // 2.创建OrderDto的分页封装器
        Page<OrdersDto> dtoPage = new Page<>();

        // 3.创建Orders的查询条件封装器
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        // 3.1 添加查询条件：按下单时间降序排列
        lqw.orderByDesc(Orders::getOrderTime);
        // 3.2 条件查询条件：按当前用户ID查询
        Long userId = BaseContext.getCurrentId();
        lqw.eq(userId != null, Orders::getUserId, userId);
        // 4.Orders分页查询
        this.page(ordersPage, lqw);

        // 5.除了Record都复制
        BeanUtils.copyProperties(ordersPage, dtoPage, "records");

        // 6.获取当前用户所有的order对象
        List<Orders> orders = this.list(lqw);
        // 7.通过stream流逐一包装成OrderDto对象
        List<OrdersDto> orderDtos = orders.stream().map(order -> {
            // 7.1 创建OrderDto对象
            OrdersDto orderDto = new OrdersDto();
            // 7.2 拷贝属性
            BeanUtils.copyProperties(order, orderDto);
            // 7.3 调用OrderDetail业务层获取订单明细集合
            LambdaQueryWrapper<OrderDetail> orderDetailLqw = new LambdaQueryWrapper<>();
            orderDetailLqw.eq(OrderDetail::getOrderId, order.getNumber());
            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailLqw);
            // 7.4 设置orderDto的订单明细属性
            orderDto.setOrderDetails(orderDetails);
            // 7.5 返回orderDto
            return orderDto;
        }).collect(Collectors.toList());

        // 8.设置dtoPage的records属性
        dtoPage.setRecords(orderDtos);
        return dtoPage;
    }


    /**
     * 用户下单
     * @param orders
     */
    @Transactional
    @Override
    public void submit(Orders orders) {

        //获取当前用户id
        Long userId = BaseContext.getCurrentId();

        //查询当前用户的购物车的数据
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);

        List<ShoppingCart> shoppingCarts = shoppingCartService.list(lambdaQueryWrapper);

        if(shoppingCarts == null || shoppingCarts.isEmpty()){
            throw new CustomException("购物车为空，不能下单");
        }

        //查询用户数据 user 表
        User user = userService.getById(userId);

        //查询地址数据  address_book表
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);

        if(addressBook == null){
            throw new CustomException("用户地址信息有误，不能下单");
        }

        long ordersId = IdWorker.getId(); //订单号

        //原子整数类  原子操作，保证线程安全
        AtomicInteger amount = new AtomicInteger(0);

        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(ordersId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue()); //订单总金额
            return orderDetail;
        }).collect(Collectors.toList());


        orders.setId(ordersId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(ordersId));
        orders.setUserName(user.getName());
        // 设置收货人姓名
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        // 设置地址详情，包含省市区
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //向订单表插入数据，一条数据
        orders.setNumber(String.valueOf(ordersId));
        this.save(orders);

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车数据
        shoppingCartService.remove(lambdaQueryWrapper);
    }

    /**
     * 再来一单
     * 前端点击再来一单是直接跳转到购物车的，所以为了避免数据有问题，再跳转之前我们需要把购物车的数据给清除
     * ①通过orderId获取订单明细
     * ②把订单明细的数据的数据塞到购物车表中，不过在此之前要先把购物车表中的数据给清除(清除的是当前登录用户的购物车表中的数据)，
     * 不然就会导致再来一单的数据有问题；
     * (这样可能会影响用户体验，但是对于外卖来说，用户体验的影响不是很大，电商项目就不能这么干了)
     *
     * @param orders
     */
    @Override
    @Transactional
    public void againOrder(Orders orders) {

        //首先需要将当前用户的购物车清空 避免数据有问题
        shoppingCartService.clean(); //封装在ShoppingCartService里了

        //将再来一单的订单明细数据放到购物车里
        //1.通过ordersId获取订单明细
        Long orderId = orders.getId();
        LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderDetail::getOrderId,orderId);

        List<OrderDetail> orderDetailList = orderDetailService.list(lambdaQueryWrapper);

        //把从order表中和order_details表中获取到的数据赋值给这个购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setName(item.getName());
            shoppingCart.setImage(item.getImage());
            shoppingCart.setUserId(BaseContext.getCurrentId());

            Long dishId = item.getDishId();
            if (dishId != null) {
                ////如果是菜品那就添加菜品的查询条件
                shoppingCart.setDishId(dishId);
                shoppingCart.setDishFlavor(item.getDishFlavor());
            } else {
                //添加到购物车的是套餐
                shoppingCart.setSetmealId(item.getSetmealId());
            }
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        //把携带数据的购物车批量插入购物车表  这个批量保存的方法要使用熟练！！！
        shoppingCartService.saveBatch(shoppingCartList);
    }
}
